﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using System.Text;

using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;

namespace WebSite.admin.order
{
    public partial class orderprocess : BaseAdmin
    {
        DALCardType theCardType = new DALCardType();

        dalCompany theCompany = new dalCompany();

        //string sMSGFormat = "阳澄湖牌大闸蟹提醒：您订购的{0}已由{1}发出，预计两日内可以收到，感谢您的订购。";

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
            this.GridViewBind("");
        }

        void BindCardType()
        {
            DataSet dsCardType = theCardType.GetList("1=1");
            this.ddlCardType.DataTextField = "Name";
            this.ddlCardType.DataValueField = "Id";
            this.ddlCardType.DataSource = dsCardType;
            this.ddlCardType.DataBind();
            this.ddlCardType.Items.Insert(0, new ListItem("请选择...", ""));

        }


        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((e.Row.RowType == DataControlRowType.Header) || (e.Row.RowType == DataControlRowType.DataRow))
            {
                CheckBox box = new CheckBox();
                box = (CheckBox)e.Row.FindControl("CheckBox1");
                if (box != null)
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                     

                        DataTable dtCards = new DataTable();
                        StringBuilder sbCardInfo = new StringBuilder();
                        dtCards = SQLAccess.GreatDs("select c.* from DB_Order o join tbOrderAccount oa "
                                                     + " on o.OrderCode = oa.OrderCode "
                                                     + " join DB_Card c on oa.cardid = c.cardid "
                                                     + " where o.ordercode='" + this.GridView1.DataKeys[e.Row.RowIndex].Value + "'").Tables[0];
                        foreach (DataRow drCard in dtCards.Rows)
                        {

                             sbCardInfo.Append(drCard["cardcode"].ToString() + ",\n");
                        }
                        e.Row.Cells[4].Text = sbCardInfo.ToString();

                        e.Row.Cells[5].Text = info.info1("", "shophuobi") + string.Format("{0:f}", Convert.ToSingle(e.Row.Cells[5].Text)) + " 元";
                        if (e.Row.Cells[8].Text.ToString() == "0")
                        {
                            e.Row.Cells[8].Text = "新订单";
                        }
                        if (e.Row.Cells[8].Text.ToString() == "1")
                        {
                            e.Row.Cells[8].Text = "备货中";
                        }
                        if (e.Row.Cells[8].Text.ToString() == "2")
                        {
                            e.Row.Cells[8].Text = "已发货";
                        }
                        if (e.Row.Cells[8].Text.ToString() == "3")
                        {
                            e.Row.Cells[8].Text = "已完成";
                        }
                        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=\"" + e.Row.Style["BACKGROUND-COLOR"] + "\"");
                        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor=\"#efefef\"");
                    }
                    else if (e.Row.RowType == DataControlRowType.Header)
                    {
                        box.Attributes.Add("onclick", "SelectAll(this.checked)");
                    }
                    e.Row.Cells[9].Visible = false;
                }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sqlsort = "";
            sqlsort = "select *,(select isnull(sum(sumprice),0) from DB_Car where orderid=o.orderid)  as sumprice from DB_order o where languages=" + info.languages("") + " ";

            sqlsort = sqlsort + GetSql();
            this.GridViewBind(sqlsort);
        }

        void BindCompanyList()
        {
            DataSet dsCompany = theCompany.GetList(" LevelId = 1");
            this.ddlCompany.DataSource = dsCompany;
            this.ddlCompany.DataTextField = "name";
            this.ddlCompany.DataValueField = "id";
            this.ddlCompany.DataBind();

            if (base.CompanyLevelId == "1")
            {
                this.ddlCompany.Items.FindByValue(base.CompanyId).Selected = true;
                this.ddlCompany.Enabled = false;
            }
        }

        private string GetSql()
        {
            string sql = "";
            if (this.ordercode.Value != "")
            {
                sql = sql + " and o.ordercode like '%" + this.ordercode.Value.ToString() + "%'";
            }
            if (this.product.Value != "")
            {
                sql = sql + " and o.orderid in(select orderid from DB_Car c join DB_Shoppro s on c.productid = s.proid  where s.proname like '%" + this.product.Value.ToString() + "%') ";
            }
            if (this.states.Value != "")
            {
                sql = sql + " and o.states=" + this.states.Value.ToString() + " ";
            }
            //if (this.spec.Value != "")
            //{
            //   sql = sql + " and o.orderid in(select orderid from DB_Car  where contents like '%" + this.product.Value.ToString() + "%') ";
            //}
            if (this.sendDateFrom.Value != "")
            {
                sql = sql + " and (o.sendDate >= '" + this.sendDateFrom.Value + "' or o.sendDate is null)";
            }
            if (this.sendDateTo.Value != "")
            {
                sql = sql + " and (o.sendDate <= '" + this.sendDateTo.Value + " 23:59' or o.sendDate is null)";
            }
            //---
             if (this.ddlProductType.SelectedItem.Value == "0")
             {
                 if (this.ddlProfessionAreaType.SelectedItem.Value != "")
                {
                      sql = sql + " and o.orderid in(select orderid from DB_Car c join DB_Shoppro s on c.productid = s.proid   where s.ProfessionAreaTypeId=" + this.ddlProfessionAreaType.SelectedItem.Value + ") ";
                 }
            }
             else if (this.ddlProductType.SelectedItem.Value == "1")
             {

                 sql = sql + " and o.orderid in(select orderid from DB_Car c join DB_Shoppro s on c.productid = s.proid   where s.proisnew4=1) ";
             }


            sql = sql + " and o.OrderCode in (select oa.orderCode from tbOrderAccount oa join DB_Card c on oa.cardId = c.CardId and c.CompanyId = " + this.ddlCompany.SelectedItem.Value  + ")";
                 //--
            if (!string.IsNullOrEmpty(this.ddlCardType.SelectedItem.Value))
            {
                sql = sql + " and o.OrderCode in (select oa.orderCode from tbOrderAccount oa join DB_Card c on oa.cardId = c.CardId and  c.CardTypeId = " + this.ddlCardType.SelectedItem.Value +")";
            }
           
            return sql;
        }

        private void GridViewBind(string Sqlsort)
        {
            string sql = "select orderid, ordercode, memberid, pay, ship, cname, tel, phone, post, address, email, [content], cname1, tel1, phone1, post1, address1, email1, content1, states, "
                     + " ordertime, paytime, shiptime, languages, totalprice, cardprice, scoreprice, orderscore, cardid, scoretype, SendCompany, SendCode, convert(varchar(10),senddate,111) as senddate, senddate1 "
                     + " ,(select isnull(sum(sumprice),0) from DB_Car where orderid=o.orderid)  as sumprice from DB_order o where languages=" + info.languages("") + " ";


            sql = sql + GetSql();

            sql = sql + " order by o.ordertime desc";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            this.GridView1.DataSource = table.DefaultView;
            this.GridView1.DataBind();
            this.LblCurrentIndex.Text = "当前第 " + ((this.GridView1.PageIndex + 1)).ToString() + "页";
            this.LblPageCount.Text = "共 " + this.GridView1.PageCount.ToString() + "页";
            this.LblRecordCount.Text = "总计 " + table.Rows.Count.ToString() + "个记录";
            this.btnFirst.Visible = true;
            this.btnPrev.Visible = true;
            this.btnNext.Visible = true;
            this.btnLast.Visible = true;
            this.LblCurrentIndex.Visible = true;
            this.LblPageCount.Visible = true;
            this.LblRecordCount.Visible = true;
            if (table.Rows.Count == 0)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = false;
                this.LblPageCount.Visible = false;
                this.LblRecordCount.Visible = false;
            }
            else if (this.GridView1.PageCount == 1)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
            }
            this.btnFirst.CommandName = "1";
            this.btnPrev.CommandName = (this.GridView1.PageIndex == 0) ? "1" : this.GridView1.PageIndex.ToString();
            this.btnNext.CommandName = (this.GridView1.PageCount == 1) ? this.GridView1.PageCount.ToString() : ((this.GridView1.PageIndex + 2)).ToString();
            this.btnLast.CommandName = this.GridView1.PageCount.ToString();
            this.ddlCurrentPage.Items.Clear();
            if (this.GridView1.PageCount > 0)
            {
                for (int i = 1; i <= this.GridView1.PageCount; i++)
                {
                    this.ddlCurrentPage.Items.Add(i.ToString());
                }
                this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
            }
        }

        private DataTable GetExportData()
        {
            string sql = "select distinct '' as 物流公司, '' as 物流单号,'' as 物流查询网址,'' as 物流查询电话,'' as 发货时间,订单号 as 寄件客户编码_订单编号,'团购部' as 寄件人,'阳澄湖大闸蟹集团公司' as 寄件公司, "
                         + " '4008850180' as 寄件人联系电话,'阳澄湖现代农业产业园' as 寄件人地址,商品名称,"
                         + " sum(pronum) as 数量,收货人,'' as 收货公司,收货人联系电话,收货地址, 备注,'' as 付款方式,'' as 保价,'\\' as 保价金额,"
                         + "'' as 代收货款,'\\' as 代收货款卡号, '' as 代收货款金额,'正宗阳澄湖牌大闸蟹' as 备注1,'' as 备注2, '' as 备注3 "                          
                         + " from  "
                         + " ( "
                         + " select O.ordercode as 订单号,"
                         + " S.proname+'(' + convert(varchar(30),S.proprice1) +')' as 商品名称,  O.cname1 as 收货人,isnull(O.tel1,'') + ';' + isnull(phone1,'') as 收货人联系电话, convert(varchar(10),O.senddate,111) as 送货日期, address1 as 收货地址,SendCompany as 物流,SendCode as 物流单号,[content] as 备注 ,C.pronum "
                         + " from DB_order O join DB_Car C on O.orderid = C.orderid join DB_Shoppro S on C.productid = S.proid "
                         + " where 1=1 ";
            sql = sql + GetSql()
                  + " ) a "
                  + " group by 订单号,收货人, 收货人联系电话,收货地址,商品名称 ,备注";
        
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }

        protected void ImageButton5_Click(object sender, ImageClickEventArgs e)
        {
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    SQLAccess.DoSql("delete from DB_order where orderid=" + this.GridView1.DataKeys[i].Value + "");
                    SQLAccess.DoSql("delete from DB_car where orderid=" + this.GridView1.DataKeys[i].Value + "");
                }
            }
            base.Response.Write("<script language=javascript>alert('更新成功！');</script>");
            this.GridViewBind("");

        }

        protected void ImageButton6_Click(object sender, ImageClickEventArgs e)
        {
            string str = "0";
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    str = str + "," + this.GridView1.DataKeys[i].Value;
                }
            }
            base.Response.Write("<script language=javascript>window.location.href='orderprocess.aspx';window.open('ordera.aspx?oid=" + str + "');</script>");
            base.Response.End();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ImageButton5.Attributes["onclick"] = "return CheckSelect(true,'del');";
            this.ImageButton6.Attributes["onclick"] = "return CheckSelect(true,'update');";
            if (!base.IsPostBack)
            {
                base.ValidateLoginRule(ERule.OrderProcess);
                if (Request.QueryString["states"] != "")
                {
                    this.states.Value = Request.QueryString["states"];
                }
                this.BindProfessionAreaType();
                this.BindCardType();
                this.BindCompanyList();
                this.GridViewBind("");
              //  this.Bind();
            }
        }

        private void BindProfessionAreaType()
        {
            DataSet dsType = new DataSet();
            DALProfessionAreaType theType = new DALProfessionAreaType();
            dsType = theType.GetList("");
            if (dsType.Tables.Count > 0)
            {
                this.ddlProfessionAreaType.DataSource = dsType.Tables[0].DefaultView;
                this.ddlProfessionAreaType.DataTextField = "Name";
                this.ddlProfessionAreaType.DataValueField = "Id";
                this.ddlProfessionAreaType.DataBind();
            }
            this.ddlProfessionAreaType.Items.Insert(0, new ListItem("所属专区", ""));


        }

        protected void PagerButtonClick(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = Convert.ToInt32(((LinkButton)sender).CommandName) - 1;
            this.GridViewBind("");
        }

        protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.GridViewBind("");
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称   
            DataTable dt = GetExportData();
            Gift.Utile.OperateExcel.ExportCSV(dt, fileName);
         
        }

        private string BuildExportHTML(System.Data.DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            int pagerecords = 5000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";

            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }





        protected void ibtnInport_Click(object sender, ImageClickEventArgs e)
        {

            if (this.FileUpload1.FileContent.Length <= 0)
            {
                Response.Write("<script>alert('请选择要导入的EXCEL文件！')</script>");
                return;
            }
            else
            {
                try
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
                    this.FileUpload1.SaveAs(Server.MapPath("../uploadTempFile/" + fileName));

                    DataTable dtResult = new DataTable();
                    dtResult = Gift.Utile.OperateExcel.InputCSV(Server.MapPath("../uploadTempFile/" + fileName));

                    DataRow[] dr = dtResult.Select();
                    int ss = dtResult.Rows.Count;
                    int rowsnum = dtResult.Rows.Count;
                    if (rowsnum == 0)
                    {
                        Response.Write("<script>alert('Excel表为空表,无数据！')</script>");
                        return;
                    }
                    int iInportSum = 0;
                    for (int i = 0; i < rowsnum; i++)
                    {
                        string orderCode = dr[i]["寄件客户编码_订单编号"].ToString();
                        string sendCompany = dr[i].Table.Columns.Contains("物流公司") ? dr[i]["物流公司"].ToString() : string.Empty;
                        string sendCode = dr[i].Table.Columns.Contains("物流单号") ? dr[i]["物流单号"].ToString() : string.Empty;
                        string sendUrl = dr[i].Table.Columns.Contains("物流查询网址") ? dr[i]["物流查询网址"].ToString() : string.Empty; 
                        string sendPerson = dr[i].Table.Columns.Contains("寄件人") ? dr[i]["寄件人"].ToString() : string.Empty; 
                        string sendPersonCompany = dr[i].Table.Columns.Contains("寄件公司") ? dr[i]["寄件公司"].ToString() : string.Empty; 
                        string sendPersonAddress = dr[i].Table.Columns.Contains("寄件人地址") ? dr[i]["寄件人地址"].ToString() : string.Empty;
                        string sendPersonTelephone = dr[i].Table.Columns.Contains("物流查询电话") ? dr[i]["物流查询电话"].ToString() : string.Empty;
                        string sendDate1 = DateTime.Now.ToString() ;
                        if (dr[i].Table.Columns.Contains("发货时间"))
                        {
                            try
                            {
                                sendDate1 = DateTime.Parse(dr[i]["发货时间"].ToString()).ToString();
                            }
                            catch
                            { }
                        }

                        
                       

                        //if (!string.IsNullOrEmpty(sendCode) )
                        //{
                            StringBuilder sbSql = new StringBuilder();
                            sbSql.AppendFormat("update DB_order set SendCode='{0}',SendCompany='{1}', SendUrl='{2}',SendPerson='{3}',SendPersonCompany='{4}',sendPersonAddress='{5}',SendTelphone='{6}',senddate1='{8}' where ordercode = {7};"
                                 , sendCode
                                 , sendCompany
                                 , sendUrl
                                 , sendPerson
                                 , sendPersonCompany
                                 , sendPersonAddress
                                 ,sendPersonTelephone
                                 , orderCode
                                 ,sendDate1
                                 );
                            sbSql.Append( "update DB_order set states=2 where ordercode = '" + orderCode + "' and ( isnull(states,0)=0 or states=1)");
                            SQLAccess.DoSql(sbSql.ToString());
                            iInportSum++;
                       // }
                       // else
                       //{
                       //     string sql = "update DB_order set states=1 where ordercode = '" + orderCode + "' and  isnull(states,0)=0";
                       //     SQLAccess.DoSql(sql);
                       //     iInportSum++;
                       // }
                    }
                    Response.Write("<script>alert('成功导入" + iInportSum.ToString() + "条用户信息！')</script>");
                    this.Dispose();
                    this.GridViewBind("");
                }
                catch (Exception ex)
                {
                    Response.Write("<script>alert('请检查Excel格式是否正确！')</script>");
                    this.Dispose();
                    this.GridViewBind("");
                }
            }
        }

        protected void ibtnUpdateStates_Click(object sender, ImageClickEventArgs e)
        {
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    if ((base.Request.Form["flag"].ToString() == "1") || (base.Request.Form["flag"].ToString() == "2"))
                    {
                        DataTable table = SQLAccess.GreatDs("select memberid,ordercode,orderscore,scoreprice,scoretype from DB_Order where orderid=" + this.GridView1.DataKeys[i].Value + "").Tables[0];
                        if ((table.Rows.Count > 0) && (table.Rows[0]["scoretype"].ToString() == "0"))
                        {
                            SQLAccess.DoSql(string.Concat(new object[] { "Update DB_Member set score1=score1+", Convert.ToInt32(table.Rows[0]["orderscore"]) - Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score2=score2-", Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score3=score3+", Convert.ToInt32(table.Rows[0]["orderscore"]), " where memberid=", table.Rows[0][0].ToString(), "" }));
                            SQLAccess.DoSql(string.Concat(new object[] { "insert into DB_Score (memberid,scorename,scoreprice,content,updatetime,scoretype) values (", table.Rows[0][0].ToString(), ",'订单赠积分：", table.Rows[0]["ordercode"], "','+", table.Rows[0]["orderscore"], "','赠积分：", table.Rows[0]["orderscore"], "','", DateTime.Now, "',0)" }));
                        }
                    }
                    SQLAccess.DoSql(string.Concat(new object[] { "Update DB_order set states=", base.Request.Form["flag"], ",scoretype=1 where orderid=", this.GridView1.DataKeys[i].Value, "" }));
                }
            }
            base.Response.Write("<script language='javascript'>alert('更新状态成功!');</script>");
            this.GridViewBind("");
        }

        protected void ibtnExport0_Click(object sender, ImageClickEventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称
         
            DataTable dt = GetExportDataForTemplate();
            Gift.Utile.OperateExcel.ExportCSV(dt, fileName);

        }

        private DataTable GetExportDataForTemplate()
        {
            string sql = "select top 0 '' as 订单号, "
                         + " '' as 送货日期,"
                         + " '' as 收件人,"
                         + " '' as 联系电话,"
                         + "'' as 送货地址,"
                         + " '' as 产品名称,"
                         + " '' as 数量,"
                         + " '' as 备注,"
                         + "'' as 物流,'' as 物流单号"
                         + " from DB_order O join DB_Car C on O.orderid = C.orderid join DB_Shoppro S on C.productid = S.proid";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }




    }
}